<?php
/**
 * My new Zend Framework project
 * 
 * @author  Radovan Dvorsky
 * @version 20100512
 */

require_once 'Zend/Controller/Plugin/Abstract.php';
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Request/Abstract.php';
require_once 'Zend/Controller/Action/HelperBroker.php';
require_once "Zend/Loader.php"; 

/**
 * 
 * Initializes configuration depndeing on the type of environment 
 * (test, development, production, etc.)
 *  
 * This can be used to configure environment variables, databases, 
 * layouts, routers, helpers and more
 *   
 */
class Initializer extends Zend_Controller_Plugin_Abstract
{	
	
	/**
	 * Path to config file
	 * @var string
	 */
	private $_configFile = 'application/config/application.xml';
	
    /**
     * @var Zend_Config
     */
    protected static $_config;

    /**
     * @var string Current environment
     */
    protected $_env;

    /**
     * @var Zend_Controller_Front
     */
    protected $_front;

    /**
     * @var string Path to application root
     */
    protected $_root;   

    /**
     * Constructor
     *
     * Initialize environment, root path, and configuration.
     * 
     * @param  string $env 
     * @param  string|null $root 
     * @return void
     */
    public function __construct($env, $root = null)
    {
        $this->_setEnv($env);
        if (null === $root) {
            $root = realpath(dirname(__FILE__) . '/../');
        }
        $this->_root = $root;

        $this->initPhpConfig();         
       
        
        $this->_front = Zend_Controller_Front::getInstance();
        
        // set the test environment parameters
        if ($env == 'test') {
			// Enable all errors so we'll know when something goes wrong. 
			error_reporting(E_ALL | E_STRICT);  
			ini_set('display_startup_errors', 1);  
			ini_set('display_errors', 1);
			$this->_front->throwExceptions(true);  
        }

		// Set up autoload.
		require_once 'Zend/Loader/Autoloader.php';	
		$autoloader = Zend_Loader_Autoloader::getInstance();
		$autoloader->registerNamespace('My_');
		$autoloader->registerNamespace('Db_');
		$autoloader->registerNamespace('Form_');
		
    }


    /**
     * Initialize environment
     * 
     * @param  string $env 
     * @return void
     */
    protected function _setEnv($env) 
    {
		$this->_env = $env;    	
    }
    
    /**
     * Load config file
     * 
     * @return void
     */
    public function initConfig(){    	
    	
    	$cache = Zend_Registry::get('configCache');
    	/*
    	 * Ak moze nacita subor z cache
    	 */
    	if(!(self::$_config = $cache->load('config'))){    		
    		self::$_config = new Zend_Config_Xml ( $this->_configFile );
    		$cache->save(self::$_config);	
    	}

    	Zend_Registry::set('config',self::$_config);
    }

    /**
     * Initialize Data bases
     * 
     * @return void
     */
    public function initPhpConfig()
    {	   	
    	date_default_timezone_set('Europe/Bratislava');    	
    	set_include_path(
	    	'.' . 
			PATH_SEPARATOR . 
			'./library' . 
			PATH_SEPARATOR . 
			'./application/default/models' .			
			PATH_SEPARATOR .
			'./application' .		
			PATH_SEPARATOR .
			get_include_path()
		);		
    }
    
    /**
     * Route startup
     * 
     * @return void
     */
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {	
    	try{
    		$this->initLogger();
    		$this->initControllers();
    		$this->initCache();
    		$this->initConfig();    		
    		$this->initControllers();	    		    	
	       	$this->initDb();
	        $this->initHelpers();
	        $this->initView();
	        $this->initPlugins();
	        $this->initRoutes();	        	               
    	} catch (Zend_Exception $e){    		
    		$log = Zend_Registry::get('log');    		
    		$log->log(get_class($e) . ':' . $e->getMessage(),Zend_Log::EMERG);
    		die('INITIALIZER ERROR: ' . get_class($e) . ':' . $e->getMessage());		
    	}
    }
    
    /**
     * Initialize data bases
     * 
     * @return void
     */
    public function initDb()
    {
    	$db = Zend_Db::factory(self::$_config->database);
		$db2 = Zend_Db::factory(self::$_config->database2);
		Zend_Db_Table::setDefaultAdapter($db);		
		$db->getConnection();
		$db2->getConnection();
		$db->query("SET NAMES 'utf8'");
		$db2->query("SET NAMES 'utf8'");
		Zend_Registry::set('db',$db);
		Zend_Registry::set('db2',$db2);		
    }

    /**
     * Initialize action helpers
     * 
     * @return void
     */
    public function initHelpers()
    {
    	// register the default action helpers
    	Zend_Controller_Action_HelperBroker::addPath('../application/default/helpers', 'Zend_Controller_Action_Helper');
    }
    
    /**
     * Initialize view 
     * 
     * @return void
     */
    public function initView()
    {
		// Bootstrap layouts
		Zend_Layout::startMvc(array(
		    'layoutPath' => $this->_root .  '/application/default/layouts',
		    'layout' => 'main'
		));
		
		$view = Zend_Layout::getMvcInstance()->getView();
		//Zend_Dojo::enableView($view);    	
		$view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
		$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
		$viewRenderer->setView($view);
		Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);   
		
		$menuCache = Zend_Registry::get('menuCache');
		if(!($config = $menuCache->load('menuCache'))){			
			$config = new Zend_Config_Xml('./application/navigation/menu.xml','nav');
			$menuCache->save($config);
		}
		
	    $container = new Zend_Navigation($config);
	    
	    $view->navigation($container);
	    
	   
    }
    
    /**
     * Initialize plugins 
     * 
     * @return void
     */
    public function initPlugins()
    {
    	
    }
    
    /**
     * Initialize routes
     * 
     * @return void
     */
    public function initRoutes()
    {
    
    }

    /**
     * Initialize Controller paths 
     * 
     * @return void
     */
    public function initControllers()
    {    	
    	$this->_front->addControllerDirectory($this->_root . '/application/default/controllers', 'default'); 	
    }
    
    public function initCache(){
    	
    	$caching = true;
    	
    	$frontendOptions = array(
			'caching' => $caching,
    		'automatic_serialization' => true,
    		'lifetime' => 7200, // cas automatickej obnovy cache 2 hod.    		
		);
				
		$frontendOptionsConfig = array(
			'automatic_serialization' => true,
			'master_files' => array(
				$this->_configFile
			)		
		);
		
		$frontendOptionsMenu = array(
			'automatic_serialization' => true,
			'master_files' => array(
				'./application/navigation/menu.xml',
			)		
		);
			
		$backendOptions = array(
		    'cache_dir' => './tmp'
		);
		
		/*
		 * Cache pre config. subor
		 */
		$configCache = Zend_Cache::factory('File','File',$frontendOptionsConfig,$backendOptions);
		
		/*
		 * Cache pre aplikaciu
		 */
		$cache = Zend_Cache::factory('Core','File',$frontendOptions,$backendOptions);
		
		/*
		 * Cache pre menu
		 */
		$menuCache = Zend_Cache::factory('File','File',$frontendOptionsMenu,$backendOptions);
		
		Zend_Registry::set('configCache',$configCache);
		Zend_Registry::set('menuCache',$menuCache);
		Zend_Registry::set('cache',$cache);
    }
    
    public function initTranslate(){
    	/*
    	 * TODO dorobit Zend_Translate
    	 */
    	
    	$config = self::$_config->translate;
    	
    	$cache = Zend_Registry::get('cache');
    	Zend_Translate::setCache($cache);
    	$translate = new Zend_Translate(
    		$config->adapter,
    		$config->slovak->filepath,
    		$config->slovak->locale
    	);
    	
    }
    
    public function initLogger(){
    	    	
    	$writer = new Zend_Log_Writer_Stream('./application/log/appLog.xml');
    	$formatter = new Zend_Log_Formatter_Xml();
    	$writer->setFormatter($formatter);    	
    	$logger = new Zend_Log($writer);
    	
    	Zend_Registry::set('log',$logger);    	
    }
   
	/**
	 * @param $_configFile the $_configFile to set
	 */
	public function setConfigFile($configFile) {
		$this->_configFile = $configFile;
	}

	/**
	 * @return the $_configFile
	 */
	public function getConfigFile() {
		return $this->_configFile;
	}
}
?>
